<template>
    <div>
      <div v-if="showLoading">
        <loading></loading>
      </div>
      <div >
        <!--//地址的组件-->
        <div style="margin-top: 0.5rem">
          <default-address v-on:childByValue="childByValue"></default-address>
        </div>
        <div v-if="!showLoading">
          <!--支付方式的组件-->
          <pay-type-choose v-on:radioValue="radioValue"></pay-type-choose>
          <div class="goods_choose white_bac flex flex_vertical_center flex_between" style="margin-top: 0.5rem" @click="openBotttomSheet">
            <div class="choose_left flex flex_vertical_center">
              <i class="fa fa-cart-arrow-down"></i>
              <p>点击更改或查看已选算商品</p>
            </div>
            <i class="fa fa-angle-right"></i>
          </div>
          <div class="bookingRemark white_bac">
            <mu-text-field class="bookingRemarkText" v-model="description" placeholder="有特殊要求请在这里备注" multi-line :rows="2" :rows-max="3"></mu-text-field>
          </div>
          <div class="accounts_foot flex flex_end">
            <p>合计支付：<span class="font-weight" style="color: #ef1336;font-size: 1rem">{{allMoney}}元</span></p>
            <button class="sure_bottom" @click="setAccounts()">
              结算
            </button>
          </div>
          <mu-bottom-sheet :open.sync="open">
            <mu-list >  <!--@item-click="closeBottomSheet"-->
              <mu-sub-header class="flex flex_between" style="margin-right: 1rem;padding: 0.5rem;background: #f1f1f1">
                <mu-button flat @click="closeBottomSheet">关闭</mu-button>
                <mu-button flat color="secondary" @click="sureChoosed">确定</mu-button>
              </mu-sub-header>
              <div class="choose_more_content">
                <div class=" white_bac pading1 order_goods flex order_border_bom" v-for="(goods,index) in goodsList">

                  <img :src="goods.goods_img">
                  <div class="goods_width">
                    <p class="flex flex_between ">
                      <span class="goods_name">{{goods.goods_name}}</span>
                    <!--<span>@@{{goods.id}}</span>-->
                    </p>
                    <p class="flex flex_between " style="color: #ff4081"><span>￥ {{goods.goods_price}}</span> </p>
                    <div class="flex flex_between">
                      <div class="flex flex_vertical_center">
                        <!--<mu-switch label="水票支付" v-model="goods.hasTickt" label-left></mu-switch>-->
                        <p style="" v-if="goods.ticketNum > 0"> 水票：<span style="color: #2196f3">{{goods.ticketNum}}</span>张 </p>
                      </div>
                      <div class="add_minus flex_center">
                        <img src="../../mall/img/minus-circle.png" v-if="goods.count > 0" @click="minusCount(goods)">
                        <span style="color: #93999f;font-size: 14px" v-if="goods.count>0">{{goods.count}}</span>

                        <img src="../../mall/img/add.png" @click="addCount(goods)">

                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </mu-list>
          </mu-bottom-sheet>
        </div>
      </div>
    </div>
</template>

<script>
    import Loading from "../../../components/loading";
    import DefaultAddress from "../../../components/components/DefaultAddress";
    import PayTypeChoose from "../../../components/components/PayTypeChoose"

    export default {
      components: {
        DefaultAddress,
        PayTypeChoose,
        Loading},
      data(){
        return{
          showLoading:true,//显示loading
          textType:0,//0 无商品时 1有商品时
          allMoney:0,
          addressChoosed:'',
          open: false,
          description:'',
          choose_waterBill:true,
          goodsList:[],
          endGoodsList: this.getCache(this.getKey('end_goods_list_')) || {},
          choosedIds: '',//表示当前打开弹框所选商品的id集合
          setAllMoney:0,
          payType:0,//支付方式 0微信  1货到
          allCount:0,
          min_num:null,
          max_num:null
        }
      },
      mounted(){
        this.initList();
        this.checkNum();
      },
      methods:{
        initList(){
          this.yesS.waterBillGoodsList(
            this.$comParams()
          ).then(res =>{

            this.goodsList = res.data;
            this.$nextTick(function () {
              this.evaluateGoodsList();
            })
          })
        },
        evaluateGoodsList(){
          if(!this.isEmpty(this.goodsList) && this.goodsList.length >0){
            for (var i=0;i<this.goodsList.length;i++){
              var goods = this.goodsList[i];
              goods.ticketNum = goods.num =  goods.count;
              if(!this.isEmpty(goods.bill_info)){
                goods.ticketNum = goods.bill_info.rest_num;
                goods.bill_id = goods.bill_info.id;
              }else {
                goods.bill_id = null;
              }
              if(!this.isEmpty(this.endGoodsList)){
                this.setAllMoney++;
                if(!this.isEmpty(this.endGoodsList[goods.id])){
                  goods.num = goods.count = this.endGoodsList[goods.id].num;
                  this.allCount += goods.count;
                }
              }
            }
          }
          this.showLoading = false
        },
        childByValue: function (childValue) {
          // childValue就是子组件传过来的值
          this.addressChoosed = childValue;
        },
        radioValue: function (childValue) {
          this.payType = childValue;
        },
        setAccounts(){
          //判断是否有地址
          if(this.addressChoosed == undefined || this.addressChoosed == null || this.addressChoosed == ''){
            this.$toast.error('还未填写地址，请点击填写');
            return;
          };
          //判断是否符合商家设定限购量
          var content ='';
          if(this.max_num >0 && this.allCount > this.max_num){
            //判断购买的商品数量是否超过最大购买数量
            content =  '最高购买数量为 '+ this.max_num +' 件';
          }
          if(this.min_num >= 1 && this.allCount < this.min_num){
            content = '最低购买数量为 ' + this.min_num +' 件';
          }
          if(this.isEmpty(content)){
            //如果满足则
            this.sureBuyEnd();
          }else {
            this.$toast.error(content);
          }
        },

        checkNum(){
          this.yesS.checkBuyNum(
            this.$comParams()
          ).then(res => {
            var buyInfo = res.data.buy_info;

            //如果不在限量中则提示
            this.min_num = buyInfo.buy_min;
            this.max_num = buyInfo.buy_max;

          })
        },
        sureBuyEnd(){

          var addressDetail = this.addressChoosed.area_info+' '+this.addressChoosed.position_address+this.addressChoosed.address;
          this.yesS.addOrderWbGoods(
            this.$combineParams({
              goods_list:this.endGoodsList,
              money:this.allMoney,
              pay_type:this.payType,
              buyer_name:this.addressChoosed.name,
              mobile:this.addressChoosed.mobile,
              buyer_address:addressDetail,
              description:this.description
            })).then(res => {
            console.log(res)
            var status = res.status;
            if(status == 1){
              this.deleteCache(this.getKey('end_goods_list_'));
              /*this.endGoodsList = {};
              this.evaluateGoodsList();*/

              if(this.payType == 1){
                //跳转到支付成功页面 查看订单
                this.$router.push({path:'/qds/success',query:{toType:1}})
              }else if(this.payType == 0 && !this.isEmpty(this.allMoney) && this.allMoney > 0){
                //调起微信支付
                this.payment(res.data);
              }

            }
          })
        },
        payment(data) {

            this.wxPay(data, 1);

        },
        isPaySuccess(data){
          this.yesS.isPaySuccess(
            this.$combineParams({id:data.id})
          ).then(res => {
            var status = 0;
            if (res.data.result != undefined) {
              status = res.data.result;
            }
            if (status) {
              this.$router.push({path:'/qds/success',query:{toType:1}});
            } else {
              this.$router.push({path:'/qds/fail',query:{toType:4}});
            }
          }).catch(res => {
            this.$toast.error('支付失败，请稍后再试')
          })
        },
        closeBottomSheet () {
          this.open = false;
          this.choosedIds ='';
        },
        openBotttomSheet () {
          this.open = true;
        },
        minusCount(obj){
          obj.count--;

          if(this.choosedIds.indexOf(','+obj.id+',') == -1){ //表示包含
           /* if(obj.count == 0){
              this.choosedIds = this.choosedIds.replace(','+obj.id +',','');//去掉这一项
            }
          }else {*/
            this.choosedIds += ','+obj.id +',';
          }

        },
        addCount(obj){
          //判断是否超标
          if(this.isEmpty(obj.count)){
            obj.count =0;
          }
          if(obj.ticketNum > 0 && obj.ticketNum <= obj.count){
            return;
          }
          obj.count++;

          if(this.choosedIds.indexOf(','+obj.id+',') == -1){ //表示不包含
            this.choosedIds += ','+obj.id +',';
          }
        },

        sureChoosed(){
          if(this.isEmpty(this.choosedIds)){
            this.closeBottomSheet();
            return;
          }
          for(var i=0;i<this.goodsList.length;i++){
            var goods = this.goodsList[i];
            if(this.choosedIds.indexOf(','+goods.id+',') != -1){//如果包含
              if(this.isEmpty(this.endGoodsList[goods.id])){
                if(goods.count > 0){
                  this.endGoodsList[goods.id] = {id:goods.id,num:goods.count,bill_id:goods.bill_id?goods.bill_id:null};
                }
              }else {
                if(goods.count > 0){
                  this.endGoodsList[goods.id].num = goods.count;
                }else {
                  delete this.endGoodsList[goods.id];
                }
              }
              this.setAllMoney++;
            }
          }

          this.setCache(this.getKey('end_goods_list_'),this.endGoodsList);
          //关闭弹框
          this.closeBottomSheet();
        },
      },
      watch:{
        open:{
          handler(curVal,oldVal){
            if(!curVal && !this.isEmpty(this.choosedIds)){
              //如果是关闭
              for(var i=0;i<this.goodsList.length;i++){
                var goods = this.goodsList[i];
                if(!this.isEmpty(this.endGoodsList[goods.id])){
                  goods.count = goods.num = this.endGoodsList[goods.id].num;
                }else {
                  goods.count = goods.num;
                }
              }
            }
          }
        },
        setAllMoney:{
          handler(curVal,oldVal){

            this.allMoney = 0;
            if(!this.isEmpty(this.goodsList) && this.goodsList.length > 0 && !this.isEmpty(this.endGoodsList)){
              for(var i=0;i<this.goodsList.length;i++){
                var goods = this.goodsList[i];
                if(!this.isEmpty(this.endGoodsList[goods.id]) && this.isEmpty(this.endGoodsList[goods.id].bill_id)){
                  this.allMoney += goods.goods_price * this.endGoodsList[goods.id].num;
                }
                if(!this.isEmpty(this.endGoodsList[goods.id])){
                  this.allCount += this.endGoodsList[goods.id].num;
                }
              }
            }

          },
          deep:true
        }
      },
    }
</script>

<style scoped>
  /*@import 'http://cdn.bootcss.com/material-design-icons/3.0.1/iconfont/material-icons.css';*/
  @import "../css/waterTickChooseMore.css";
</style>
